package com.xb.cloud.gateway.filter;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xb.cloud.common.JsonUtils;
import com.xb.cloud.common.redis.CacheUtil;
import com.xb.cloud.common.util.DateUtils;
import com.xb.cloud.common.util.StringUtils;
import com.xb.cloud.gateway.client.Context;
import com.xb.cloud.gateway.client.RtnCodes;
import com.xb.cloud.gateway.core.RtnInfoCreater;
import com.xb.cloud.product.merchant.service.client.bo.EndMerchantUserBo;
import com.xb.cloud.user.service.client.bo.EndUserBo;

public class UserTokenFilter implements GatewayFilter {
	Logger logger = LoggerFactory.getLogger(UserTokenFilter.class);

	/**
	 * 这个值应该和user-center-api相同
	 */
	public final int EXPIRE_USERTOKEN_MINUTE_60 = 60 * 60;
	public final int DIFF_USERTOKEN_MINUTE_10 = 10;
	public final String USERTOKEN_KEY = "usertoken_%s";
	public final String MERCHANTUSERTOKEN_KEY = "merchantusertoken_%s";

	@Override
	public void init() {
	}

	@Override
	public void doFilter(Context xbContext, GatewFilterChain chain) {
		boolean isMerchantLogin = false;

		if (xbContext.isCheckToken()) {
			String userToken = xbContext.getRequestInfo().getUserToken();
			String merchantUserToken = xbContext.getRequestInfo().getMerchantUserToken();

			String tokenKey = "";
			if (StringUtils.isBlank(merchantUserToken)) {
				tokenKey = String.format(USERTOKEN_KEY, userToken);
			} else {
				isMerchantLogin = true;
				tokenKey = String.format(MERCHANTUSERTOKEN_KEY, merchantUserToken);
			}

			if (CacheUtil.exists(tokenKey)) {
				String userStr = (String) CacheUtil.getex(tokenKey);

				if (!isMerchantLogin) {
					EndUserBo endUserBO = JsonUtils.toObject(userStr, EndUserBo.class);
					if (endUserBO == null) {
						xbContext.setRtnInfo(RtnInfoCreater.InvokeInBoundHandleError(RtnCodes.USER_TOKEN_ERROR));
					} else {
						xbContext.setCurrentUserId(endUserBO.getId());
						Date cacheUtDate = endUserBO.getEndUserLastLoginDate();
						int diffMinutes = DateUtils.getDiffMinutes(cacheUtDate);

						if (diffMinutes > DIFF_USERTOKEN_MINUTE_10) {
							// 距离上次活动时间大于10分钟，自动续命userToken
							CacheUtil.del(tokenKey);
							endUserBO.setEndUserLastLoginDate(new Date());
							CacheUtil.setex(tokenKey, EXPIRE_USERTOKEN_MINUTE_60, endUserBO);
						}
					}
				} else {
					// 商家端登录
					EndMerchantUserBo merchantUserBo = JsonUtils.toObject(userStr, EndMerchantUserBo.class);
					if (merchantUserBo == null) {
						xbContext.setRtnInfo(RtnInfoCreater.InvokeInBoundHandleError(RtnCodes.USER_TOKEN_ERROR));
					} else {
						xbContext.setCurrentMerchantUserId(merchantUserBo.getId());
						Date cacheUtDate = merchantUserBo.getAdminUserLastLoginDate();
						int diffMinutes = DateUtils.getDiffMinutes(cacheUtDate);

						if (diffMinutes > DIFF_USERTOKEN_MINUTE_10) {
							// 距离上次活动时间大于10分钟，自动续命userToken
							CacheUtil.del(tokenKey);
							merchantUserBo.setAdminUserLastLoginDate(new Date());
							CacheUtil.setex(tokenKey, EXPIRE_USERTOKEN_MINUTE_60, merchantUserBo);
						}
					}
				}

			} else {
				xbContext.setRtnInfo(RtnInfoCreater.InvokeInBoundHandleError(RtnCodes.USER_TOKEN_ERROR));
			}
		}

		chain.doFilter(xbContext);
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public void destroy() {

	}

}
